<%@ page import="java.util.List" %>
<%@ page import="java.util.regex.Matcher" %>
<%@ page import="java.util.regex.Pattern" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    List<Map<String,String>> users =new ArrayList<Map<String,String>>();
    Map user1 = new HashMap();
    user1.put("name","牛蛙");
    user1.put("url","http://my.oschina.net/lujianing");

    Map user2 = new HashMap();
    user2.put("name","黄勇");
    user2.put("url","http://my.oschina.net/huangyong");

    Map user3 = new HashMap();
    user3.put("name","悠悠然然");
    user3.put("url","http://my.oschina.net/tinyframework");


    Map user4 = new HashMap();
    user4.put("name","红薯");
    user4.put("url","http://my.oschina.net/javayou");

    users.add(user1);
    users.add(user2);
    users.add(user3);
    users.add(user4);

    request.setCharacterEncoding("utf-8");
    String content = request.getParameter("content");
    out.print(_GenerateRefererLinks(content,users));
%>


<%!

    static Pattern referer_pattern = Pattern.compile("@([^@^\\s^:]{1,})([\\s\\:\\,\\;]{0,1})");//@.+?[\\s:]

    /**
     * 处理提到某人 @xxxx
     * @param msg  传入的文本内容
     * @return 返回带有链接的文本内容
     */
    public static String _GenerateRefererLinks(String msg,List<Map<String,String>> users) {
        StringBuilder html = new StringBuilder();
        int lastIdx = 0;
        Matcher matchr = referer_pattern.matcher(msg);
        while (matchr.find()) {
            String origion_str = matchr.group();

            String str = origion_str.substring(1, origion_str.length()).trim();

            html.append(msg.substring(lastIdx, matchr.start()));


            Map<String,String> user =null;

            for(Map<String,String> u:users){
                if(u.get("name").equals(str)){
                    user =u;
                }
            }
            if(user!=null){
                html.append("<a href='"+user.get("url")+"' class='referer' target='_blank'>@");
                html.append(str.trim());
                html.append("</a>");
            }else{
                html.append(origion_str);
            }
            lastIdx = matchr.end();
        }
        html.append(msg.substring(lastIdx));
        return html.toString();
    }
%>